package com.zz.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zz.common.Log;
import com.zz.common.R;
import com.zz.entity.UserRole;
import com.zz.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * @author 朱彦燕
 * 用户角色管理
 */
@RestController
@RequestMapping("/userRole")
@Slf4j
@CrossOrigin
@Validated
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 朱彦燕
     * 根据条件 分页 展示所有用户角色
     * 测试
     */
    @RequiresRoles("admin")
    @GetMapping("/page")
    //@Cacheable(value="roleCache",key="'role'+#page+#pageSize+#userName+#roleRealName",sync = true)
    @Log(title = "根据条件 分页 展示所有用户角色", dataLocationType = "link")
    public R<Page> page(@RequestParam @NotNull(message = "起始页码不能为空") int page,
                        @RequestParam @NotNull(message = "每页最大数不能为空") int pageSize,
                        @RequestParam @Nullable String userName,
                        @RequestParam @Nullable String roleRealName) {

        return userRoleService.page(page, pageSize, userName, roleRealName);
    }


    /**
     * @param userRole 删除用户角色
     * 测试成功
     */
    @RequiresRoles("admin")
    @DeleteMapping("/delete")
    @CacheEvict(value = "roleCache",allEntries = true)
    public R<String> deleteUserRole(@RequestBody @Validated(Delete.class) UserRole userRole) {
        return userRoleService.deleteUserRole(userRole);
    }

    /**
     * @param userRole 增加用户角色
     * 测试成功
     */
    @RequiresRoles("admin")
    @PostMapping("/add")
    @CacheEvict(value = "roleCache",allEntries = true)
    public R<String> addUserRole(@RequestBody @Validated({Insert.class}) UserRole userRole) {
        return userRoleService.addUserRole(userRole);
    }

    /**
     * @param userRole 修改用户角色
     * 朱彦燕
     * 测试成功
     */
    @RequiresRoles("admin")
    @PutMapping("/update")
    @CacheEvict(value = "roleCache",allEntries = true)
    public R<String> updateUserRole(@RequestBody @Valid UserRole userRole) {
        return userRoleService.updateUserRole(userRole);
    }

}